<?php
/*  Copyright 2012 Abu Saebu
	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

*/
add_action( "get_header", 'res_get_head' );

$paypal_buttons = array('small' => 'https://www.paypal.com/en_US/i/btn/btn_paynow_SM.gif',
	'large' => 'https://www.paypal.com/en_US/i/btn/btn_paynow_LG.gif',
	'cards' => 'https://www.paypal.com/en_US/i/btn/btn_paynowCC_LG.gif');
	

function res_get_head()
{

if ($_REQUEST['pager']=='payonlinesystem') {wp_redirect(payonlinesystem()); }
if ($_REQUEST['pager']=='confirm_pos') {$payconfirm=confirm_pos(); wp_redirect(get_option("res_pay_pos_ReturnUrl")."?payconfirm=".urlencode($payconfirm));        }
if ($_REQUEST['pager']=='confirm_robo') {$payconfirm=confirm_robo(); wp_redirect(get_option("res_pay_pos_ReturnUrl")."?payconfirm=".urlencode($payconfirm));        }
}


function mobcash()
{

	global $wpdb;

	$from=get_option("res_pay_mobcash_from") ;
	$lifetime=get_option("res_pay_mobcash_lifetime") ;
	$summar=floor($_REQUEST["summa"]);
	$summak=($_REQUEST["summa"]-$summar)*100;
	$orderid=$_REQUEST["orderid"];


	$qry ="update ".$wpdb->prefix . "res_orders"." set  paysys='1'  where  orderid='$orderId'";
	$wpdb->query($wpdb->prepare($qry) );	


	$content = <<<EOF
	<br>
	<script type="text/javascript">
	var ie=document.all;var moz=(navigator.userAgent.indexOf("Mozilla")!=-1);var opera=window.opera;var brodilka="";if(ie&&!opera){brodilka="ie"}else{if(moz){brodilka="moz"}else{if(opera){brodilka="opera"}}}var inputMasks=new Array();function kdown(a,c){var e=a.getAttribute("id");var b=e.substring(0,e.length-1);var d=Number(e.substring(e.length-1));inputMasks[b].BlKPress(d,a,c)}function kup(a,b){if(Number(a.getAttribute("size"))==a.value.length){var f=a.getAttribute("id");var d=f.substring(0,f.length-1);var e=Number((f.substring(f.length-1)))+1;var c=document.getElementById(d+e);if(b!=8&&b!=9){if(c){c.focus()}}else{if(b==8){a.value=a.value.substring(0,a.value.length-1)}}}}function Mask(d){var c="(\\d{3})\\d{3}-\\d{2}-\\d{2}";var f=[];var g=[];var a=[];var e="";d.style.display="none";var b=function(k){var j=Number(k.substring(3,k.indexOf("}")));var i=d.getAttribute("id");var m=g.length;var l="";var h=function(n){return((n>=48)&&(n<=57))||((n>=96)&&(n<=105))||(n==27)||(n==8)||(n==9)||(n==13)||(n==45)||(n==46)||(n==144)||((n>=33)&&(n<=40))||((n>=16)&&(n<=18))||((n>=112)&&(n<=123))};this.makeInput=function(){return"<input type='text' size='"+j+"' maxlength='"+j+"' id='"+i+m+"' onKeyDown='kdown(this, event)' onKeyUp='kup(this, event.keyCode)' value='"+l+"'>"};this.key=function(n,q){if(opera){return}if(!h(q.keyCode)){switch(brodilka){case"ie":q.cancelBubble=true;q.returnValue=false;break;case"moz":q.preventDefault();q.stopPropagation();break;case"opera":break;default:}return}if(q.keyCode==8&&n.value==""){var s=n.getAttribute("id");var r=s.substring(0,s.length-1);var o=Number(s.substring(s.length-1))-1;var p=document.getElementById(r+o);if(p!=null){p.focus()}}};this.getText=function(){l=document.getElementById(i+m).value;return l};this.setText=function(n){l=n};this.getSize=function(){return j}};this.drawInputs=function(){var k="<span class='Field'>";var l=0;var h=0;for(var j in a){if(a[j]=="p"){k+=f[l];l++}else{k+=g[h].makeInput();h++}}k+="</span>";document.getElementById("div_"+d.getAttribute("id")).innerHTML=k};this.buildFromFields=function(){var i=c;while(i.indexOf("\\")!=-1){var h=i.indexOf("\\");var k="";if(i.substring(0,h)!=""){f[f.length]=i.substring(0,h);a[a.length]="p";i=i.substring(h)}var j=i.indexOf("}");g[g.length]=new b(i.substring(0,j+1),k);i=i.substring(j+1);a[a.length]="b"}if(i!=""){f[f.length]=i;a[a.length]="p"}this.drawInputs()};this.buildFromFields();this.BlKPress=function(j,h,i){g[j].key(h,i)};this.makeHInput=function(){var h=d.getAttribute("name");document.getElementById("div_"+d.getAttribute("id")).innerHTML="<input type='text' readonly='readonly' name='"+h+"' value='"+this.getValue()+"'>"};this.getFName=function(){return d.getAttribute("name")};this.getValue=function(){e="";var k=0;var h=0;for(var j in a){if(a[j]!="p"){e+=g[h].getText();h++}}return e};this.check=function(){for(var h in g){if(g[h].getText().length==0){return false}}return true}};
	</script>
	</head>
	<body>
	<div style="margin:0 auto; padding:5px; width:450px; border:1px solid #333; background:#000; border-radius: 7px; -webkit-border-radius: 7px; -moz-border-radius: 7px; font:normal 14px/14px Geneva,Verdana,Arial,Helvetica,Tahoma,sans-serif;">
EOF
	.'      <form action="http://www.mobw.ru/setInetBill.do" method="post" onSubmit="return checkSubmit();">
	
		<input type="hidden" name="from" value="'.$from.'"/>
		<input type="hidden" name="lifetime" value="'.$lifetime.'"/>
		<input type="hidden" name="check_agt" value="false"/>
		<input type="hidden" name="txn_id" value="'.$orderid.'"/>
		
		<p style="text-align:center; color:#d8b580; padding:20px 0px; background:url(http://ishop.qiwi.ru/img/button/logo_31x50.jpg) no-repeat 10px 50%;">Выставить счёт за покупку</p>
		<table style="border-collapse:collapse;">
			<tr style="">
				<td style="color:#d8b580; width:45%; text-align:center; padding:10px 0px;">Мобильный телефон (пример: 9057772233)</td>
				<td style="padding:10px">
					<input type="text" name="to" id="idto" style="width:130px; border: 1px inset #555;"></input>
					<span id="div_idto"></span>
					<script type="text/javascript">
						inputMasks["idto"] = new Mask(document.getElementById("idto"));
						function checkSubmit() {
							if (inputMasks["idto"].getValue().match(/^\d{10}$/)) {
								document.getElementById("idto").setAttribute("disabled", "disabled");
								inputMasks["idto"].makeHInput();
								return true;
							} else {
								alert("Введите номер телефона в федеральном формате без \"8\" и без \"+7\"");
								return false;
							}
						}
					</script>
				</td>
			</tr>
			<tr>
				<td style="color:#d8b580; padding:10px 0px; width:45%; text-align:center;">Сумма</td>
				<td style="padding:10px">
					<input type="text" readonly name="amount_rub" value="'.$summar.'" maxlength="4" style="width:50px; text-align:right;  border: 1px inset #555;" /> руб. 
					<input type="text" readonly  name="amount_kop" value="'.$summak.'" maxlength="2" size="2" style="text-align:right; border: 1px inset #555;"/> коп.
				</td>
			</tr>
			<tr style="">
				<td style="color:#d8b580; padding:10px 0px; width:45%; text-align:center;">Комментарий</td>
				<td style="padding:10px"><textarea  readonly  rows="2" cols="30" name="com" style="width:200px; border: 1px inset #555;">Оплата бронирования по счёту №'.$orderid.'</textarea></td>
			</tr>
		</table>
		<p style="text-align:center;"><input type="submit" value="Выставить счёт" style=" padding:10px 0;border:none; background:url(http://ishop.qiwi.ru/img/button/superBtBlue.jpg) no-repeat 0 50%; color:#000; width:300px;"/></p>
	</form>
</div>';

return $content;

}

function payonlinesystem()

{
	global $wpdb;



	$merchantId =  	get_option("res_pay_pos_merchantId");
	$ReturnUrl = urlencode(get_option("res_pay_pos_ReturnUrl"));
	$securityKey = get_option("res_pay_pos_securityKey");
	$orderId = $_REQUEST["orderid"];
	$amount = sprintf("%.02f",$_REQUEST['summa']);
	$currency = "RUB";
	
	$pager="confirm_pos";
	
	$qry ="update ".$wpdb->prefix . "res_orders"." set  paysys='2'  where  orderid='$orderId'";
	$wpdb->query($wpdb->prepare($qry) );	
	
	
	$baseQuery = "MerchantId=".$merchantId.
	"&OrderId=".$orderId.
	"&Amount=".$amount.
	"&Currency=".$currency;

	$queryWithSecurityKey = $baseQuery."&PrivateSecurityKey=".$securityKey;

	$hash = md5($queryWithSecurityKey);

	
	$clientQuery = $baseQuery."&SecurityKey=".$hash."&pager=".$pager;

	$paymentFormAddress = "https://secure.payonlinesystem.com/ru/payment/?".$clientQuery;

	return $paymentFormAddress;
	
}	

function confirm_pos	() {

	global $wpdb;
	$merchantId =  	get_option("res_pay_pos_merchantId");
	$orderId = $_REQUEST['OrderId'];
	$amount = $_REQUEST['Amount'];
	$DateTime = $_REQUEST['DateTime'];
	$TransactionID = $_REQUEST['TransactionID'];
	$currency = $_REQUEST['Currency'];
	$PrivateSecurityKey = get_option("res_pay_pos_ReturnUrl");
	$SecurityKey = $_REQUEST['SecurityKey'];

	$baseQuery = "DateTime=".$DateTime.
	"&TransactionID=".$TransactionID.
	"&OrderId=".$orderId.
	"&Amount=".$amount.
	"&Currency=".$currency;

	$queryWithSecurityKey = $baseQuery."&PrivateSecurityKey=".$PrivateSecurityKey;
	
	
	$hash = md5($queryWithSecurityKey);
	
	
	if  ($hash == $SecurityKey) { 
		$content = __("Payment was completed successfully.","mb-reservation"); 
		$qry ="update ".$wpdb->prefix . "res_orders"." set payed='1' , paysys='2'  where  orderid='$orderId'";
			$wpdb->query($wpdb->prepare($qry) );	
		
		
	} else $content=__("Oops! Your payment failed, please try again.
 If you have trouble finishing this reservation, please call us
+31(0)20 622 7970 or
 email us mikesbiketoursamsterdam@yahoo.com
 Thank you.
","mb-reservation");
	
	return $content;
}

function sber	() {

	global $wpdb;
	$orderid = $_REQUEST['orderid'];
	$summa = $_REQUEST['summa'];
	
	$qry ="update ".$wpdb->prefix . "res_orders"." set  paysys='3'  where  orderid='$orderId'";
	$wpdb->query($wpdb->prepare($qry) );	
	
	$content = <<<EOF
	<h3>Квитанция Сбербанка</h3>

	<form action="" method="post" target="_blank" >
	<input type="hidden" name="pager" value="sberprint">

	<div class='label'>Фамилия, имя, отчество плательщика</div>
	<div class='field'><input type="text" name="namefio" class='w'></div>
	<br>
	<div class='label'>Адрес регистрации плательщика</div>
	<div class='field'><input type="text" name='address' class='w'></div>
	<br>
	<div class='label'>Сумма</div>
	<div class='field'><input type="text" readonly name="summa" value="$summa"></div>
	<input type='hidden' name='orderid' value="$orderid">
	<br>
	<div><input type="submit" value="Сформировать и распечатать"></div>

	</form>
EOF;
return $content;
}

function sberprint	() {
	$summar=floor($_REQUEST['summa']);
	$summak=($_REQUEST['summa']-$summar)*100;
	$orderid=$_REQUEST['orderid'];
	$name=$_REQUEST['namefio'];
	$address=$_REQUEST['address'];

	$company=get_option("res_pay_sber_company");
	$inn=get_option("res_pay_sber_INN");
	$bank_account=get_option("res_pay_sber_bank_account");
	$bank_name=get_option("res_pay_sber_bank_name");
	$bik=get_option("res_pay_sber_bik");
	$cor_acc=get_option("res_pay_sber_cor_acc");

	$content = <<<EOF

	<html>

	<head>
	<meta http-equiv='content-type' content='text/html; charset=UTF-8'>
	<title>Квитанция на оплату</title>
	
	</head>

	<style>

	body {margin:0; padding:0; color: #000;  background-color: #fff; }
	table {margin:0; padding:0; border-spacing: 0px; border-collapse: collapse; }
	form { margin: 0px; padding: 0px;}
	a {color: #000;}

	h1 {margin: 0 0 0.8em 0; font-weight: normal; font-size: 2em; color: #000;}

	.w {width: 100%;}
	.h {height: 100%;}

	.cb {clear: both;}
	.fl {float: left;}
	.fr {float: right;}

	.tac {text-align: center;}
	.tal {text-align: left;}
	.tar {text-align: right;}
	.vam {vertical-align: middle;}
	.vab {vertical-align: bottom;}

	.label {margin: 0 0 0.5em 0; color: #000;}
	.field {margin: 0 0 1.5em 0;}

	.receipt-fields {width: 600px; padding: 40px; margin: 0 auto 0 auto;}
	.receipt {width:680px; margin: 0 auto 0 auto; color: #000;}
	.receipt td {border: 1px solid #000;}
	.left {width:190px;}
	.right {padding:10px;}

	.back {width:680px; margin: 0 auto 20px auto; color: #000;}

	.f0 {margin: 20px 0 190px 0;}
	.f12 {padding: 0 0 10px 0;}
	.f2, .f4, .f5, .f6, .f8, .f9, .f10, .f11, .f13, .f17, .f18, .f19 {font-size:9pt;}
	.f1, .f3, .f4 span, .f5 span, .f6 span, .f13 {font-size:7pt;}
	.f2, .f4 div, .f5 div, .f6 div, .f10, .f18, .f19 {border-bottom: 1px solid #000;}
	.f1, .f3, .f4, .f5, .f6, .f7, .f8, .f9, .f10, .f11, .f19 {margin-bottom: 6px;}

	.f4, .f5 {width: 225px;}
	.f6 {width: 265px;}
	.f7 {width: 185px;}
	.f17 {width: 30px;}
	.f18 {width: 155px;}
	.f8 {width: 240px;}
	.f19 {width: 220px;}
	.f9 {width: 130px;}
	.f10 {width: 330px;}

	@media print {
		.back {display: none;}
		.receipt {color: #000;}
		.receipt td {border: 1px solid #000;}
		.f2, .f4 div, .f5 div, .f6 div, .f10, .f18, .f19 {border-bottom: 1px solid #000;}
	}

	</style>

	<body>

	<table class='w h'>
	<tr>
	<td class='tac vam'>


	<div class='back tal'><a href="javascript:void(0);" onClick="window.print();">Печать</a>
	</div>

	<table class='receipt'>
	<tr>
	<td class='left tac'>
	<div class='f0'>Извещение</div>
	<div>Кассир</div>
	</td>
	<td class='right'>

	<div class='f1 fr'>Форма № ПД-4</div>

	<div class='f2 cb tac'>$company</div>
	<div class='f3 tac'>(наименование получателя платежа)</div>

	<div class='f4 fl tac'><div>$inn</div><span>(ИНН получателя платежа)</span></div>
	<div class='f5 fr tac'><div>$bank_account</div><span>(номер счета получателя платежа)</span></div>

	<div class='f6 fl tac'><div>$bank_name</div><span>(наименование банка получателя платежа)</span></div>
	<div class='f7 fr'><div class='f17 fl'>БИК</div><div class='f18 fl tac'>$bik</div></div>

	<div class='cb'></div>

	<div class='f8 fl'>Номер кор./сч. банка получателя платежа</div>
	<div class='f19 fr tac'>$cor_acc</div>

	<div class='cb'></div>

	<div class='f4 fl tac'><div>Оплата бронирования по счету №$orderid</div><span>(наименование платежа)</span></div>
	<div class='f5 fr tac'><div>&nbsp;</div><span>(номер лицевого счета (код) плательщика)</span></div>

	<div class='f9 fl'>Ф.И.О. плательщика:</div>
	<div class='f10 fl tac'>$name</div>

	<div class='f9 fl'>Адрес плательщика:</div>
	<div class='f10 fl tac'>$address</div>

	<div class='f11'>Сумма платежа: $summar руб. $summak коп.</div>

	<div class='f11'>19.11.2009 г.</div>

	<div class='f13'><b>Подпись плательщика</b></div>
	
	</td>
	</tr>
	<tr>
	<td class='tac vab'>
	<div class='f12'>Квитанция</div>
	<div class='f12'>Кассир</div>
	</td>
	<td class='right'>

	<div class='f2 cb tac'>$company</div>
	<div class='f3 tac'>(наименование получателя платежа)</div>

	<div class='f4 fl tac'><div>$inn</div><span>(ИНН получателя платежа)</span></div>
	<div class='f5 fr tac'><div>$bank_account</div><span>(номер счета получателя платежа)</span></div>

	<div class='f6 fl tac'><div>$bank_name</div><span>(наименование банка получателя платежа)</span></div>
	<div class='f7 fr'><div class='f17 fl'>БИК</div><div class='f18 fl tac'>$bik</div></div>

	<div class='cb'></div>

	<div class='f8 fl'>Номер кор./сч. банка получателя платежа</div>
	<div class='f19 fr tac'>$cor_acc</div>

	<div class='cb'></div>

	<div class='f4 fl tac'><div>Оплата бронирования по счету №$orderid</div><span>(наименование платежа)</span></div>
	<div class='f5 fr tac'><div>&nbsp;</div><span>(номер лицевого счета (код) плательщика)</span></div>

	<div class='f9 fl'>Ф.И.О. плательщика:</div>
	<div class='f10 fl tac'>$name</div>

	<div class='f9 fl'>Адрес плательщика:</div>
	<div class='f10 fl tac'>$address</div>

	<div class='f11'>Сумма платежа: $summar руб. $summak коп.</div>

	<div class='f11'>19.11.2009 г.</div>

	<div class='f13'><b>Подпись плательщика</b></div>
	
	</td>
	</tr>
	</table>

	</body>

	</html>




EOF;
 return $content;
}

function webmoney () {

	global $wpdb;
	$purse =  get_option("res_pay_webmoney_purse");
	$orderid = $_REQUEST['orderid'];
	$summa = $_REQUEST['summa'];
	
	
	$qry ="update ".$wpdb->prefix . "res_orders"." set  paysys='5'  where  orderid='$orderId'";
	$wpdb->query($wpdb->prepare($qry) );	
	
	$text=base64_encode(__("Reservation order #","mb-reservation")."$orderid");
	
	
	
	$content =  '
<h3>Оплата через webmoney</h3>
<form   id=pay name=pay method="POST" action="https://merchant.webmoney.ru/lmi/payment.asp">
<table cellpadding="3" align="left"><tr><td><b>'.$title.'</b></td><td>
	<input type="hidden" name="LMI_PAYMENT_AMOUNT" value="'.$summa.'"  >
	<input type="hidden" name="LMI_PAYMENT_DESC" value="'.$text.'">
	<input type="hidden" name="LMI_PAYMENT_DESC_BASE64" value="'.$text.'">	
	<input type="hidden" name="LMI_PAYMENT_NO" value="'.$orderid.'">
	<input type="hidden" name="LMI_PAYEE_PURSE" value="'.$purse.'">
	<input type="hidden" name="LMI_SIM_MODE" value="0">
	<input type="submit" value="Оплатить '.$summa.' WM'.substr($purse, 0, 1).'">
	</td></tr></table>
</form>
';
return $content ;
}

function robokassa	() {

	global $wpdb;
	$orderid = $_REQUEST["orderid"];
	$text=__("Reservation order #","mb-reservation")."$orderid";
	
	$qry ="update ".$wpdb->prefix . "res_orders"." set  paysys='4'  where  orderid='$orderId'";
	$wpdb->query($wpdb->prepare($qry) );	
	
	// your registration data
	$mrh_login = get_option("res_pay_robokassa_mrh_login");      // your login here
	$mrh_pass1 = get_option("res_pay_robokassa_mrh_pass1");   // merchant pass1 here

	// order properties
	$inv_id    = $_REQUEST["orderid"];        // shop's invoice number 
	// (unique for shop's lifetime)
	$inv_desc  = $text;   // invoice desc
	$out_summ  = $_REQUEST["summa"];   // invoice summ

	// build CRC value
	$crc  = md5("$mrh_login:$out_summ:$inv_id:$mrh_pass1");

	// build URL

	$url = "https://merchant.roboxchange.com/Index.aspx";

	$content =  '

	<h3>'.__("Payment via","mb-reservation").' RoboKassa.</h3>

	<form   id=pay name=pay method="POST" action="'.$url.'">
	<table cellpadding="3" align="center"><tr><td><b>'.$title.'</b></td><td>
	<input type="hidden" name="MrchLogin" value="'.$mrh_login.'"  >
	<input type="hidden" name="OutSum" value="'.$out_summ.'">
	<input type="hidden" name="InvId" value="'.$inv_id.'">	
	<input type="hidden" name="Desc" value="'.$text.'">
	<input type="hidden" name="SignatureValue" value="'.$crc.'">
	<input type="submit" value="'.__("Pay now","mb-reservation").' '.$out_summ.' RUB">
	</td></tr></table>
	</form>	

';

return $content;

}

function confirm_robo	() {


	global $wpdb;
	
	if  ($_REQUEST['success'] == 1) { 
		$content = __("Payment was completed successfully.","mb-reservation"); 
		$qry ="update ".$wpdb->prefix . "res_orders"." set payed='1' , paysys='2'  where  orderid='".$_REQUEST['InvId']."'";
		$wpdb->query($wpdb->prepare($qry) );	

		
		
	} else $content=__("Payment failed.","mb-reservation");

	return $content;
}

function paypal () {

	
	
	global $wpdb,  $paypal_buttons;
	$orderid = $_REQUEST["orderid"];
	$text=__("Reservation order #","mb-reservation")."$orderid";
	
	$qry ="update ".$wpdb->prefix . "res_orders"." set  paysys='6'  where  orderid='$orderId'";
	$wpdb->query($wpdb->prepare($qry) );	
	
	// your registration data
	$merchantId = get_option("res_pay_paypal_merchantId");      // your login here
	
	// order properties
	$item_number = $_REQUEST["orderid"];        // shop's invoice number 
	$item_name = $text;   // invoice desc
	$amount = $_REQUEST["summa"];   // invoice summ
	$return = get_option("res_pay_paypal_return");
	$cancel_return = get_option("res_pay_paypal_cancel_return");
	$notify_url = get_option("res_pay_paypal_notify_url");
	
	$currency_code = get_option("res_pay_paypal_currency");
	
	$button_localized = get_option("res_pay_paypal_button_localized");
	if (get_option("res_pay_paypal_button_localized"))
	{ $button_localized = get_option("res_pay_paypal_button_localized"); } else { $button_localized = 'en_US'; }
	if ( get_option('res_pay_paypal_button') == "custom" )
	$button_url = get_option('res_pay_paypal_button_url');
	else
	$button_url = str_replace('en_US', $button_localized, $paypal_buttons[get_option('res_pay_paypal_button')]);



	$url = "https://www.paypal.com/cgi-bin/webscr";
	//$url = "https://www.sandbox.paypal.com/cgi-bin/webscr";

	$content = '
	<strong>'.__("Payment via","mb-reservation").' PayPal</strong>

	<form   id=pay name=pay method="POST" action="'.$url.'">
	<table cellpadding="3" align="left"><tr><td><b>'.$title.'</b></td><td>
	<input type="hidden" name="cmd" value="_xclick"  >
	<input type="hidden" name="business" value="'.$merchantId.'">
	<input type="hidden" name="item_name" value="'.$item_name.'">	
	<input type="hidden" name="item_number" value="'.$item_number.'">
	<input type="hidden" name="amount" value="'.$amount.'">
	<input type="hidden" name="currency_code" value="'.$currency_code.'">
	<input type="hidden" name="return" value="'.$return.'?pager=success_paypal">
	<input type="hidden" name="cancel_return" value="'.$cancel_return.'?pager=cancel_paypal">
	<input type="hidden" name="notify_url" value="'.$notify_url.'?pager=confirm_paypal">
	<input type="image" src="' .$button_url. '" name="submit" alt="PayPal - The safer, easier way to pay online." />
	</td></tr></table>
	</form>	

';

return $content;

}


function confirm_paypal	() {


	global $wpdb;
	
	
 $merchantId = get_option("res_pay_paypal_merchantId"); 
 $currency_code = get_option("res_pay_paypal_currency");
 
 $url = "https://www.paypal.com/cgi-bin/webscr";
 //$url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
  
  
  //  request confirm trancaction  
  
  $postdata=""; 
  foreach ($_POST as $key=>$value) $postdata.=$key."=".urlencode($value)."&";  
  $postdata.="cmd=_notify-validate"; 
  $curl = curl_init($url); 
  curl_setopt ($curl, CURLOPT_HEADER, 0); 
  curl_setopt ($curl, CURLOPT_POST, 1); 
  curl_setopt ($curl, CURLOPT_POSTFIELDS, $postdata); 
  curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, 0); 
  curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1); 
  curl_setopt ($curl, CURLOPT_SSL_VERIFYHOST, 1); 
  $response = curl_exec ($curl); 
  curl_close ($curl);  
  
  if ($response != "VERIFIED") return false;  

  
  if ($_POST['receiver_email'] != $merchantId      ) 
        return false;	
	
	
	
	if  (isset($_REQUEST['item_number'])) { 
		$content = __("Payment was completed successfully.","mb-reservation"); 
		$qry ="update ".$wpdb->prefix . "res_orders"." set payed='1' , paysys='6'  where  orderid='".$_REQUEST['item_number']."'";
		$wpdb->query($wpdb->prepare($qry) );	

		
		
	} else return false;

	return true;
}

function success_paypal	() {


	global $wpdb;
	
	$content=__("Payment was completed successfully.","mb-reservation"); 

	return $content;
}

function cancel_paypal	() {


	global $wpdb;
	
	$content=__("Oops! Your payment failed, please try again.
 If you have trouble finishing this reservation, please call us
+31(0)20 622 7970 or
 email us mikesbiketoursamsterdam@yahoo.com
 Thank you.","mb-reservation");

	return $content;
}




/////////////////////////////////////////////////////////////////////////////
//					User page section							//
/////////////////////////////////////////////////////////////////////////////

function res_user_page()
{
	if ( !is_user_logged_in() )  {
		//input name and pass and click "Login"
		$content = '<p>'.__("Enter your username and password then click \"Login\"","mb-reservation").'</p> 
<form action="'. get_option("home").'/wp-login.php" method="post">

	<table width=400  ><tr><td width=200><label for="log">'.__("Login (email)","mb-reservation").'</label></td><td><input type="text" name="log" id="log" value="'. wp_specialchars(stripslashes($user_login), 1) .'" size="20" /></td></tr>

	<tr><td><label for="pwd">'.__("Password","mb-reservation").'</label></td><td><input type="password" name="pwd" id="pwd" size="20" /></td></tr>

	<tr><td></td><td><input type="submit" name="submit" value="'.__("Login","mb-reservation").'" class="button" /></td></tr></table>

	<p>
	<input name="rememberme" id="rememberme" type="hidden"  value="forever" /> 
	<input type="hidden" name="redirect_to" value="'.get_page_link().'" />
	</p> 
</form>
<a href="'. get_option("home"). '/wp-login.php?action=lostpassword">'.__("Password recovery","mb-reservation").'</a>';
		$_REQUEST['pager']="auth";}

	switch ($_REQUEST['pager']) {
		//case 'show_orders' : echo cancel_order(); break;
	case 'cancel' : $content .= cancel_order(); break;
	case 'contpay': $content .= payment($_REQUEST['orderid'],$_REQUEST['sumprice']); break;
	case 'mobcash': $content .= mobcash();        break ; 
	case 'sber': $content .= sber();        break ; 
	case 'sberprint': $content .= sberprint();        break ; 
	case 'webmoney': $content .= webmoney ();        break ; 
	case 'robokassa': $content .= robokassa ();        break ; 
	case 'paypal': $content .= paypal ();        break ; 
	case 'confirm_paypal': $content .=confirm_paypal(); break;  
	case 'success_paypal': $content .=success_paypal(); break; 
	case 'cancel_paypal': $content .=cancel_paypal(); break; 
	case 'nopay': $content .= "<div class=alert>".__("You have not chosen a payment system","mb-reservation")."</div>"; $content .= page3 ();break ; 
	default:  $content .= show_orders();        break;
	}
	echo $content;
}



function show_orders () {
	global $wpdb, $current_user, $payconfirm;
		
	if ($_REQUEST['message']) 
	{
		//wp_mail(  get_userdata($_REQUEST['userid'])->user_email , $_REQUEST['subject'], $_REQUEST['message']);
		wp_mail(  get_userdata( 1 )->user_email , __("Cancel order #","mb-reservation"). $_REQUEST['orderid']." от ".$_REQUEST['last_name']." ".$_REQUEST['first_name'] , $_REQUEST['message']);
		$content .= "<div class=alert>".__("Cancellation message  sent to administrator","mb-reservation")."</div>"		 ;
	}

	$qry="select orderid, userid , price , datebegin, dateend, comments , paysys, name,  payed,
max((if(meta_key = 'first_name', meta_value, NULL ))) first_name,
max((if(meta_key = 'last_name', meta_value, NULL ))) last_name,
max((if(meta_key = 'nickname', meta_value, NULL ))) nickname from
".$wpdb->prefix . "usermeta inner join ".$wpdb->prefix . "res_orders on (userid = user_id)
left join ".$wpdb->prefix . "res_paysys on (paysys = paysysid)
where meta_key in ('first_name','last_name','nickname' ) and userid=$current_user->ID
group by orderid, userid , price , datebegin, dateend, comments , paysys, payed,name
";

	$results=$wpdb->get_results($wpdb->prepare($qry), ARRAY_A);

	if (count($results)>0) {	

		
		$pageadr=$_REQUEST['page'];

		if (isset($_REQUEST['payconfirm'])) $content .= "<div class=alert>".$_REQUEST['payconfirm']."</div>";
		$content .= '

	<br>
	<form id="form" name="form" method="post" action="">
	<table class="res" >
	<thead>
	<tr >

	<th width=40>№</th>
	
	<th width=100>'.__("Order value","mb-reservation").'</th>
	<th width=100>'.__("Start date","mb-reservation").'</th>
	<th width=100>'.__("End date","mb-reservation").'</th>
	<th width=80>'.__("Paid","mb-reservation").'</th>
	<th width=80>'.__("Pay now","mb-reservation").'</th>
	<th width=80>'.__("Cancel","mb-reservation").'</th>
	</tr>
	</thead>
';

		$pageadr=$_REQUEST['page'];
		if (count($results)>0) {
			$i=1;$rowflag=1;
			foreach ($results as $fld) {

				extract($fld);

				$payedadder="";
				if ($payed > 0) $payedadder="checked";

				$content .= <<<EOF
				<tr class="row$rowflag" >    
				<td>$orderid
				<input type="hidden" name="orderid[$i]" value="$orderid" />
				<input type="hidden" name="userid[$i]" value="$userid" />
				</td>
				<td><input type="hidden" name="price[$i]" value="$price"  />$price</td>
				<td>$datebegin</td>
				<td>$dateend</td>
				<td><input type="checkbox" disabled $payedadder name="payed[$i]" value="1"  /></td>
				<td>
EOF;

				if ($payed == 0) $content .= "<a href=\"?pager=contpay&orderid=$orderid&sumprice=$price\">".__("Pay now","mb-reservation");
				
				$content .= <<<EOF
				</a></td>
				<td><a href="?pager=cancel&last_name=$last_name&first_name=$first_name&orderid=$orderid">
EOF
				.__("Cancel","mb-reservation").
				<<<EOF
				</a></td>

				</tr>
EOF;
				$i++; $rowflag = $rowflag*(-1);
			}
		}


		$content .= <<<EOF

		</table>


		</form>
EOF;
	}
	else
	$content=__("You don't have a reservation","mb-reservation");
	return 	$content;
}

function cancel_order ()
{
	global $post;
	$content="";
	$var = $_REQUEST;
	foreach ( $var as $key => $value ) {
		$$key = trim(htmlspecialchars(strip_tags($value)));}



	


	$content.='	<br>'.
	sprintf(__("Cancel Order <b>#%s</b>  ","mb-reservation"),$orderid).
	'<form id="form" name="form" method="post" action="">
	<input type=hidden name=last_name value="'.$last_name.'">
	<input type=hidden name=first_name value="'.$first_name.'">
	<input type=hidden name=pager value="show_orders">
	<input type=hidden name=orderid value="'.$orderid.'">
	<br>'.__("Enter the reason for cancellation","mb-reservation").'<br>
	<textarea cols=70 rows=10 name=message></textarea>
	<br><br><input type=submit value="'	.__("Send","mb-reservation").'"></form>	';


	return $content;
}


function pro_update_settings()
{
	update_option("res_advance_payment_in_percents",$_REQUEST["res_advance_payment_in_percents"]) ;
	update_option("res_pay_pos_enabled",$_REQUEST["res_pay_pos_enabled"]) ;
	update_option("res_pay_pos_merchantId",$_REQUEST["res_pay_pos_merchantId"]) ;
	update_option("res_pay_pos_ReturnUrl",$_REQUEST["res_pay_pos_ReturnUrl"]) ;
	update_option("res_pay_pos_securityKey",$_REQUEST["res_pay_pos_securityKey"]) ;
	update_option("res_pay_robokassa_enabled",$_REQUEST["res_pay_robokassa_enabled"]) ;
	update_option("res_pay_robokassa_mrh_login",$_REQUEST["res_pay_robokassa_mrh_login"]) ;
	update_option("res_pay_robokassa_mrh_pass1",$_REQUEST["res_pay_robokassa_mrh_pass1"]);
	update_option("res_pay_sber_enabled",$_REQUEST["res_pay_sber_enabled"]);
	update_option("res_pay_sber_company",$_REQUEST["res_pay_sber_company"]);
	update_option("res_pay_sber_inn",$_REQUEST["res_pay_sber_inn"]);
	update_option("res_pay_sber_bank_account",$_REQUEST["res_pay_sber_bank_account"]) ;
	update_option("res_pay_sber_bank_name",$_REQUEST["res_pay_sber_bank_name"]) ;
	update_option("res_pay_sber_bik",$_REQUEST["res_pay_sber_bik"]) ;
	update_option("res_pay_sber_cor_acc",$_REQUEST["res_pay_sber_cor_acc"]) ;
	update_option("res_pay_webmoney_enabled",$_REQUEST["res_pay_webmoney_enabled"]) ;
	update_option("res_pay_webmoney_purse",$_REQUEST["res_pay_webmoney_purse"]) ;
	update_option("res_pay_mobcash_enabled",$_REQUEST["res_pay_mobcash_enabled"]) ;
	update_option("res_pay_mobcash_from",$_REQUEST["res_pay_mobcash_from"]) ;
	update_option("res_pay_mobcash_lifetime",$_REQUEST["res_pay_mobcash_lifetime"]) ;
	update_option("res_pay_paypal_enabled",$_REQUEST["res_pay_paypal_enabled"]) ;
	update_option("res_pay_paypal_merchantId",$_REQUEST["res_pay_paypal_merchantId"]) ;
	update_option("res_pay_paypal_return",$_REQUEST["res_pay_paypal_return"]) ;
	update_option("res_pay_paypal_cancel_return",$_REQUEST["res_pay_paypal_cancel_return"]) ;
	update_option("res_pay_paypal_notify_url",$_REQUEST["res_pay_paypal_notify_url"]) ;	
	update_option("res_pay_paypal_currency",$_REQUEST["res_pay_paypal_currency"]) ;
	update_option("res_pay_paypal_button",$_REQUEST["res_pay_paypal_button"]) ;
	update_option("res_pay_paypal_button_localized",$_REQUEST["res_pay_paypal_button_localized"]) ;
	update_option("res_pay_paypal_button_url",$_REQUEST["res_pay_paypal_button_url"]) ;
	update_option("res_mail_admin_email",$_REQUEST["res_mail_admin_email"]) ;
	update_option("res_mail_admin_subject",$_REQUEST["res_mail_admin_subject"]) ;
	update_option("res_mail_admin_message",$_REQUEST["res_mail_admin_message"]) ;
	update_option("res_mail_client_subject",$_REQUEST["res_mail_client_subject"]) ;
	update_option("res_mail_client_message",$_REQUEST["res_mail_client_message"]) ;
	
}

function pro_settings ()
{	
global $paypal_buttons;
	
	$localized_buttons = array('en_AU' => 'Australia - Australian English',
	'de_DE/AT' => 'Austria - German',
	'nl_NL/BE' => 'Belgium - Dutch',
	'fr_XC' => 'Canada - French',
	'zh_XC' => 'China - Simplified Chinese',
	'fr_FR/FR' => 'France - French',
	'de_DE/DE' => 'Germany - German',
	'it_IT/IT' => 'Italy - Italian',
	'ja_JP/JP' => 'Japan - Japanese',
	'es_XC' => 'Mexico - Spanish',
	'nl_NL/NL' => 'Netherlands - Dutch',
	'pl_PL/PL' => 'Poland - Polish',
	'es_ES/ES' => 'Spain - Spanish',
	'de_DE/CH' => 'Switzerland - German',
	'fr_FR/CH' => 'Switzerland - French',
	'en_US' => 'United States - U.S. English');
	$currency_codes = array('AUD' => 'Australian Dollars (A $)',
	'CAD' => 'Canadian Dollars (C $)',
	'EUR' => 'Euros (&euro;)',
	'GBP' => 'Pounds Sterling (&pound;)',
	'JPY' => 'Yen (&yen;)',
	'USD' => 'U.S. Dollars ($)',
	'NZD' => 'New Zealand Dollar ($)',
	'CHF' => 'Swiss Franc',
	'HKD' => 'Hong Kong Dollar ($)',
	'SGD' => 'Singapore Dollar ($)',
	'SEK' => 'Swedish Krona',
	'DKK' => 'Danish Krone',
	'PLN' => 'Polish Zloty',
	'NOK' => 'Norwegian Krone',
	'HUF' => 'Hungarian Forint',
	'CZK' => 'Czech Koruna',
	'ILS' => 'Israeli Shekel',
	'MXN' => 'Mexican Peso');									

	$res_pay_paypal_button_localized=get_option("res_pay_paypal_button_localized");
	$res_pay_paypal_button=get_option("res_pay_paypal_button");
	$res_pay_paypal_currency=get_option("res_pay_paypal_currency");
	
	$content = '
	<br>
	<h3>'.__("settings","mb-reservation").'</h3>
	
	<table class="widefat page fixed" style="width:650px">
	<thead>
	<tr >
	<th >'.__("Parameter","mb-reservation").'</th>
	<th>'.__("Value","mb-reservation").'</th>
	</tr>
	</thead>
	<tr>
	<td>'.__("Advance payment of the total order by  in percents (%).<br> Default 100%","mb-reservation").'</td>
	<td><input type="text" name="res_advance_payment_in_percents"  size=43  value="'.get_option("res_advance_payment_in_percents") .'" /></td>
	</tr>
	</table>
	
	<br><h3>'.__("Confirmation mails","mb-reservation").'</h3>
	
	<table class="widefat page fixed" style="width:650px">
	<thead>
	<tr >
	<th >'.__("Parameter","mb-reservation").'</th>
	<th>'.__("Value","mb-reservation").'</th>
	</tr>
	</thead>
	<tr>
	<td>'.__("Admin email","mb-reservation").'</td>
	<td><input type="text" name="res_mail_admin_email"  size=43  value="'.get_option("res_mail_admin_email") .'" /></td>
	</tr>
	<tr>
	<td>'.__("Admin subject","mb-reservation").'</td>
	<td><input type="text" name="res_mail_admin_subject"  size=43  value="'.get_option("res_mail_admin_subject") .'" /></td>
	</tr>
	<tr>
	<td>'.__("Admin message","mb-reservation").'</td>
	<td><textarea   name="res_mail_admin_message" rows="10" cols="40">'.get_option("res_mail_admin_message") .'</textarea ></td>
	</tr>
	
	<tr>
	<td>'.__("Client subject","mb-reservation").'</td>
	<td><input type="text" name="res_mail_client_subject"  size=43  value="'.get_option("res_mail_client_subject") .'" /></td>
	</tr>
	<tr>
	<td>'.__("Client message","mb-reservation").'</td>
	<td><textarea   name="res_mail_client_message" rows="10" cols="40">'.get_option("res_mail_client_message") .'</textarea ></td>
	</tr>
	</table>
	
	<div class="paypal" >
	<br>
	<h3><a target="blank" href="http://www.paypal.com/">'.__("Paypal","mb-reservation").'</a></h3>
	
	<table class="widefat page fixed" style="width:650px">
	<thead>
	<tr >
	<th >'.__("Parameter","mb-reservation").'</th>
	<th>'.__("Value","mb-reservation").'</th>
	</tr>
	</thead>
	<tr>
	<td>'.__("Enabled","mb-reservation").'</td>
	<td><input type="checkbox"  name="res_pay_paypal_enabled"'; 
	if(get_option("res_pay_paypal_enabled"))  $content.=' checked ';
	$content.='" /></td>
	</tr>
	<tr>
	<td>'.__("Your PayPal email address or merchant account ID","mb-reservation").'</td>
	<td><input type="text" name="res_pay_paypal_merchantId"  size=43  value="'.get_option("res_pay_paypal_merchantId") .'" /></td>
	</tr>
	<tr>
	<td>'.__("Success URL","mb-reservation").'</td>
	<td><input type="text" name="res_pay_paypal_return" size=43 value="'.get_option("res_pay_paypal_return") .'" /></td>
	</tr>
	<tr>
	<td>'.__("Cancel URL","mb-reservation").'</td>
	<td><input type="text" name="res_pay_paypal_cancel_return"  size=43  value="'.get_option("res_pay_paypal_cancel_return") .'" /></td>
	</tr>
	<tr>
	<td>'.__("Confirm URL","mb-reservation").'</td>
	<td><input type="text" name="res_pay_paypal_notify_url"  size=43  value="'.get_option("res_pay_paypal_notify_url") .'" /></td>
	</tr>
	<tr>
	<td>'.__("Currency","mb-reservation").'</td>
	<td>';
	$content.='<select name="res_pay_paypal_currency" id="res_pay_paypal_currency">';
	if (isset($res_pay_paypal_currency)) { $current_currency = $res_pay_paypal_currency; } else { $current_currency = 'USD'; }
	foreach ( $currency_codes as $key => $code ) {
		$content.= '<option value="'.$key.'"';
		if ($current_currency == $key) { $content.= ' selected="selected"'; }
		$content.= '>'.$code.'</option>';
	}
	$content.='</select>';
	
	$content.='</td>
	</tr>	
	<tr>
	<td>'.__("Pay button","mb-reservation").'</td>
	<td>';
	
	
	$custom = TRUE;
	if (!empty($res_pay_paypal_button_localized)) { $button_localized = $res_pay_paypal_button_localized; } else { $button_localized = 'en_US'; };
	if (isset($res_pay_paypal_button)) { $current_button = $res_pay_paypal_button; } else { $current_button = 'large'; };
	foreach ( $paypal_buttons as $key => $button ) {
		$content.= "\t<label title='" . attribute_escape($key) . "'><input style='padding: 10px 0 10px 0;' type='radio' name='res_pay_paypal_button' value='" . attribute_escape($key) . "'";
		if ( $current_button === $key ) { // checked() uses "==" rather than "==="
			$content.= "checked='checked'";
			$custom = FALSE;
		}
		$content.= " /> <img src='" . str_replace('en_US', $button_localized, $button) . "' alt='" . $key  . "' style='vertical-align: middle;' /></label><br /><br />\n";
	}
	$content.=__('Button language', 'mb-reservation'). ' <select name="res_pay_paypal_button_localized" id="res_pay_paypal_button_localized">';
	foreach ( $localized_buttons as $key => $localize ) {
		$content.='<option value="'.$key.'"';
		if ($button_localized == $key) { $content.= ' selected="selected"'; }
		$content.= '>'.$localize.'</option>';
	} 
	$content.='</select><br /><br />';
	
	$content.= '	<label><input type="radio" name="res_pay_paypal_button" value="custom"';
	$content.= checked( $custom, TRUE, FALSE );
	$content.= '/> ' . __('Custom Button', 'mb-reservation') . ' </label><br>';
	
	$content.='
	<input type="text" size=43  name="res_pay_paypal_button_url" value="'.get_option("res_pay_paypal_button_url") .'"  />
	</td>
	</tr>
	</table>
	
	</div>';
/*	
	<br>
	<h3><a target="blank"  href="http://www.payonlinesystem.com/">'.__("PayOnlineSystem (Visa, MasterCard, American Express, Diners Club)","mb-reservation").'</a></h3>
	
	<table class="widefat page fixed" style="width:650px">
	<thead>
	<tr >
	<th >'.__("Parameter","mb-reservation").'</th>
	<th>'.__("Value","mb-reservation").'</th>
	</tr>
	</thead>
	<tr>
	<td>'.__("Enabled","mb-reservation").'</td>
	<td><input type="checkbox"  name="res_pay_pos_enabled"'; 
	if(get_option("res_pay_pos_enabled"))  $content.=' checked ';
	$content.='" /></td>
	</tr>
	<tr>
	<td>'.__("merchantId","mb-reservation").'</td>
	<td><input type="text" name="res_pay_pos_merchantId"  size=43  value="'.get_option("res_pay_pos_merchantId") .'" /></td>
	</tr>
	<tr>
	<td>'.__("ReturnUrl","mb-reservation").'</td>
	<td><input type="text" name="res_pay_pos_ReturnUrl" size=43 value="'.get_option("res_pay_pos_ReturnUrl") .'" /></td>
	</tr>
	<tr>
	<td>'.__("securityKey","mb-reservation").'</td>
	<td><input type="text" name="res_pay_pos_securityKey"  size=43  value="'.get_option("res_pay_pos_securityKey") .'" /></td>
	</tr>
	</table>
	
<br>
	<h3><a target="blank" href="http://robokassa.com/">'.__("Robokassa (Yandex.Money, MoneyMail, RBK Money, SMS, Visa, MasterCard ...)","mb-reservation").'</a></h3>
	
	<table class="widefat page fixed" style="width:650px">
	<thead>
	<tr >
	<th >'.__("Parameter","mb-reservation").'</th>
	<th>'.__("Value","mb-reservation").'</th>
	</tr>
	</thead>
	<tr>
	<td>'.__("Enabled","mb-reservation").'</td>
	<td><input type="checkbox"  name="res_pay_robokassa_enabled"'; 
	if(get_option("res_pay_robokassa_enabled"))  $content.=' checked ';
	$content.='" /></td>
	</tr>
	<tr>
	<td>'.__("mrh_login","mb-reservation").'</td>
	<td><input type="text" name="res_pay_robokassa_mrh_login"  size=43  value="'.get_option("res_pay_robokassa_mrh_login") .'" /></td>
	</tr>
	<tr>
	<td>'.__("mrh_pass1","mb-reservation").'</td>
	<td><input type="text" name="res_pay_robokassa_mrh_pass1"  size=43  value="'.get_option("res_pay_robokassa_mrh_pass1") .'" /></td>
	</tr>
	</table>		
	
<br>
	<h3><a target="blank" href="http://sbrf.ru/en/">'.__("SberBank","mb-reservation").'</a></h3>
	
	<table class="widefat page fixed" style="width:650px">
	<thead>
	<tr >
	<th >'.__("Parameter","mb-reservation").'</th>
	<th>'.__("Value","mb-reservation").'</th>
	</tr>
	</thead>
	<tr>
	<td>'.__("Enabled","mb-reservation").'</td>
	<td><input type="checkbox"  name="res_pay_sber_enabled"'; 
	if(get_option("res_pay_sber_enabled"))  $content.=' checked ';
	$content.='" /></td>
	</tr>
	<tr>
	<td>'.__("Company name","mb-reservation").'</td>
	<td><input type="text" name="res_pay_sber_company"  size=43  value="'.get_option("res_pay_sber_company") .'" /></td>
	</tr>
	<tr>
	<td>'.__("INN","mb-reservation").'</td>
	<td><input type="text" name="res_pay_sber_inn" size=43 value="'.get_option("res_pay_sber_inn") .'" /></td>
	</tr>
	<tr>
	<td>'.__("Bank account","mb-reservation").'</td>
	<td><input type="text" name="res_pay_sber_bank_account"  size=43  value="'.get_option("res_pay_sber_bank_account") .'" /></td>
	</tr>
	<tr>
	<td>'.__("Bank name","mb-reservation").'</td>
	<td><input type="text" name="res_pay_sber_bank_name"  size=43  value="'.get_option("res_pay_sber_bank_name") .'" /></td>
	</tr>
	<tr>
	<td>'.__("BIK","mb-reservation").'</td>
	<td><input type="text" name="res_pay_sber_bik"  size=43  value="'.get_option("res_pay_sber_bik") .'" /></td>
	</tr>
	<tr>
	<td>'.__("Correspondent account","mb-reservation").'</td>
	<td><input type="text" name="res_pay_sber_cor_acc"  size=43  value="'.get_option("res_pay_sber_cor_acc") .'" /></td>
	</tr>
	</table>	
	
	<br>
	<h3><a target="blank" href="http://webmoney.com/">'.__("Webmoney","mb-reservation").'</a></h3>
	
	<table class="widefat page fixed" style="width:650px">
	<thead>
	<tr >
	<th >'.__("Parameter","mb-reservation").'</th>
	<th>'.__("Value","mb-reservation").'</th>
	</tr>
	</thead>
	<tr>
	<td>'.__("Enabled","mb-reservation").'</td>
	<td><input type="checkbox"  name="res_pay_webmoney_enabled"'; 
	if(get_option("res_pay_webmoney_enabled"))  $content.=' checked ';
	$content.='" /></td>
	</tr>
	<tr>
	<td>'.__("Webmoney purse","mb-reservation").'</td>
	<td><input type="text" name="res_pay_webmoney_purse"  size=43  value="'.get_option("res_pay_webmoney_purse") .'" /></td>
	</tr>
	</table>
	
	<br>
	<h3><a target="blank" href="https://ishop.qiwi.ru/">'.__("Mobcash, QIWI","mb-reservation").'</a></h3>
	
	<table class="widefat page fixed" style="width:650px">
	<thead>
	<tr >
	<th >'.__("Parameter","mb-reservation").'</th>
	<th>'.__("Value","mb-reservation").'</th>
	</tr>
	</thead>
	<tr>
	<td>'.__("Enabled","mb-reservation").'</td>
	<td><input type="checkbox"  name="res_pay_mobcash_enabled"'; 
	if(get_option("res_pay_mobcash_enabled"))  $content.=' checked ';
	$content.='" /></td>
	</tr>
	<tr>
	<td>'.__("Registration number","mb-reservation").'</td>
	<td><input type="text" name="res_pay_mobcash_from"  size=43  value="'.get_option("res_pay_mobcash_from") .'" /></td>
	</tr>
	<tr>
	<td>'.__("Lifetime bill in hours","mb-reservation").'</td>
	<td><input type="text" name="res_pay_mobcash_lifetime"  size=43  value="'.get_option("res_pay_mobcash_lifetime") .'" /></td>
	</tr>
	</table>';
*/
	return $content;
}

function pro_paysys_list()
{
	
	if ( get_option("res_pay_paypal_enabled") || get_option("res_pay_pos_enabled") || get_option("res_pay_robokassa_enabled") || get_option("res_pay_sber_enabled") || get_option("res_pay_webmoney_enabled") || get_option("res_pay_mobcash_enabled") ) {

		$content .= '<br>
	<h3>'.__("Pay Order","mb-reservation").'</h3>
	<table width="300" style="text-align:left;">';
		if ( get_option("res_pay_paypal_enabled"))	$content.='<tr>
	<td><label>
	<input type="radio" name="pager" value="paypal" />
	'.__("PayPal","mb-reservation").'</label></td>
	</tr>';
		if ( get_option("res_pay_pos_enabled"))	$content.='<tr>
	<td><label>
	<input type="radio" name="pager" value="payonlinesystem" />
	'.__("PayOnlineSystems","mb-reservation").'</label></td>
	</tr>';
		if ( get_option("res_pay_robokassa_enabled"))	$content.='<tr>
	<td><label>
	<input type="radio" name="pager" value="robokassa" />
	'.__("RoboKassa","mb-reservation").'</label></td>
	</tr>';
		if ( get_option("res_pay_sber_enabled"))	$content.='<tr>
	<td><label>
	<input type="radio" name="pager" value="sber" />
'.__("Sberbank","mb-reservation").'
	</label></td>
	</tr>';
		if ( get_option("res_pay_webmoney_enabled"))	$content.='<tr>
	<td><label>
	<input type="radio" name="pager" value="webmoney" />
	Webmoney</label></td>
	</tr>';
		if ( get_option("res_pay_mobcash_enabled"))	$content.='<tr>
	<td><label>
	<input type="radio" name="pager" value="mobcash" />
'.__("Mob cash","mb-reservation").'
	</label></td>
	</tr>';
		$content.='<tr>
	<td><label>
	
	<input type="submit" name="button" id="button" value=" '.__("Continue","mb-reservation").' "  >
	</label></td>
	
	</tr>
	</table>';
	} 
	else {
		$content.="<b>".__("Thank you for your order","mb-reservation")."</b>";
	} 
	
	return $content;
}

function pro_add_settings()
{
	add_option("res_advance_payment_in_percents", "100");
	add_option("res_pay_mobcash_enabled", "on");
	add_option("res_pay_mobcash_from", "1111");
	add_option("res_pay_mobcash_lifetime", "240");
	add_option("res_pay_pos_enabled", "on");
	add_option("res_pay_pos_merchantId", "111");
	add_option("res_pay_pos_ReturnUrl", "http://reservation.isaev.asia/demo/reservation/");
	add_option("res_pay_pos_securityKey", "13e2a93d-2bab-443c-a0ce-4ae5809bfx1a");
	add_option("res_pay_webmoney_enabled", "on");
	add_option("res_pay_webmoney_purse", "R698612052562");
	add_option("res_pay_robokassa_enabled", "on");
	add_option("res_pay_robokassa_mrh_login", "login");
	add_option("res_pay_robokassa_mrh_pass1", "pass");
	add_option("res_pay_sber_enabled","on");
	add_option("res_pay_sber_company","Company name");
	add_option("res_pay_sber_inn","280109970000");
	add_option("res_pay_sber_bank_account","40802810731620000000") ;
	add_option("res_pay_sber_bank_name","Rosbank public company") ;
	add_option("res_pay_sber_bik","041012715") ;
	add_option("res_pay_sber_cor_acc","30101810800000000715") ;
	add_option("res_pay_paypal_enabled","on") ;
	add_option("res_pay_paypal_merchantId","info@isaev.asia") ;
	add_option("res_pay_paypal_return","http://reservation.isaev.asia/demo/reservation/") ;
	add_option("res_pay_paypal_cancel_return","http://reservation.isaev.asia/demo/reservation/") ;
	add_option("res_pay_paypal_notify_url","http://reservation.isaev.asia/demo/reservation/") ;
	add_option("res_pay_paypal_currency","USD") ;
	add_option("res_pay_paypal_button","cards") ;
	add_option("res_pay_paypal_button_localized","") ;
	add_option("res_pay_paypal_button_url","http://reservation.isaev.asia/demo/images/paybtn.png") ;
	add_option("res_mail_admin_email","your@site.admin.com") ;
	add_option("res_mail_admin_subject","New order on your site") ;
	add_option("res_mail_admin_message","You have a new order #[num] from [datebegin] to [dateend]") ;
	add_option("res_mail_client_subject","Order accepted") ;
	add_option("res_mail_client_message","Thank you for your order! For your order to create an account. Your Login [login] Your password [password]") ;
	
	
	
}

function pro_delete_settings()
{
	delete_option("res_advance_payment_in_percents");
	delete_option("res_pay_mobcash_enabled");
	delete_option("res_pay_mobcash_from");
	delete_option("res_pay_mobcash_lifetime");
	delete_option("res_pay_pos_enabled");
	delete_option("res_pay_pos_merchantId");
	delete_option("res_pay_pos_ReturnUrl");
	delete_option("res_pay_pos_securityKey");
	delete_option("res_pay_webmoney_enabled");
	delete_option("res_pay_webmoney_purse");
	delete_option("res_pay_robokassa_enabled");
	delete_option("res_pay_robokassa_mrh_login");
	delete_option("res_pay_robokassa_mrh_pass1");
	delete_option("res_pay_sber_enabled");
	delete_option("res_pay_sber_company");
	delete_option("res_pay_sber_inn");
	delete_option("res_pay_sber_bank_account") ;
	delete_option("res_pay_sber_bank_name") ;
	delete_option("res_pay_sber_bik") ;
	delete_option("res_pay_sber_cor_acc") ;
	delete_option("res_pay_paypal_enabled") ;
	delete_option("res_pay_paypal_merchantId") ;
	delete_option("res_pay_paypal_return") ;
	delete_option("res_pay_paypal_cancel_return") ;
	delete_option("res_pay_paypal_notify_url") ;
	delete_option("res_pay_paypal_currency") ;
	delete_option("res_pay_paypal_button") ;
	delete_option("res_pay_paypal_button_localized") ;
	delete_option("res_pay_paypal_button_url") ;
	delete_option("res_mail_admin_email") ;
	delete_option("res_mail_admin_subject") ;
	delete_option("res_mail_admin_message") ;
	delete_option("res_mail_client_subject") ;
	delete_option("res_mail_client_message") ;
	
	
	
}

function show_user_fields($user)
{
	$content="";
	$content.='<h3>'.__("Additional fields (mb-reservation)","mb-reservation").'</h3>
			<table class="form-table">';

	$phone = get_the_author_meta('phone', $user->ID);
	$content.='<tr>
					<th><label for="description">'.__("Phone","mb-reservation").'</label></th>
					<td><input class="regular-text" type="text" name="phone" value="'.esc_attr($phone).'" /></td></tr>';
	$address = get_the_author_meta('address', $user->ID);
	
	$content.='<tr>
					<th><label for="description">'.__("Address","mb-reservation").'</label></th>
					<td><input class="regular-text" type="text" name="address" value="'.esc_attr($address).'" /></td></tr>';

	$content.='</table>';
	echo $content;
}


function update_user_fields($user_id)
{
	update_usermeta($user_id, 'phone', esc_attr($_REQUEST["phone"]) );
	update_usermeta($user_id, 'address', esc_attr($_REQUEST["address"]) );

}

function check_fields ()
{
	$err = "";
	if ($_REQUEST['phone']=="") {
		$err .= __(" - Not specified (Telephone Number)","mb-reservation"); }
	return $err;					
}

function check_fields_js ()
{
return <<<EOF
			
			if (obj.phone.value=="") {
				err += "
EOF
.__(" - Not specified (Telephone Number)","mb-reservation").
<<<EOF
			";
			}
EOF;
}

function phone_row() { return "<tr ><td>".__("Phone","mb-reservation")."</td><td><input type=text name=phone value=\"".$_REQUEST['phone']."\"></td></tr>";}


function pro_res_insert($content) {
	global $wpdb;

	if (preg_match('{RESERVATION(\+|\-)([0-9\, ]+)}',$content,$plarr))
	{
		// get array elements after {RESERVATION+
		$plarr1=$plarr[1];
		$plarr=explode(",",$plarr[2]);
		
		$charr= charr ($plarr1, $plarr);
		
		$res_output = res_page($charr,1);
		
		$content = preg_replace('/{RESERVATION(\+|\-)([0-9\, ]+)}/',$res_output,$content);
		
	}
	if (preg_match('{RESUSERPAGE}',$content))
	{
		$res_output = res_user_page(); 
		
		$content = str_replace('{RESUSERPAGE}',$res_output,$content);
		
	}
	return $content;
}

function pro_page1_qry($charr)
{
global $wpdb;

if ($charr[0]=="-") $adder=" NOT ";
return "   from  
	".$wpdb->prefix . "res_orders  c
INNER JOIN  ".$wpdb->prefix . "res_orders_content   b 
ON (c.orderid =
	b.orderid)
	RIGHT JOIN  ".$wpdb->prefix . "res_resources   a ON (b.resourceid =
	a.resourceid)
	LEFT JOIN ".$wpdb->prefix . "res_offers d ON (d.resourceid = a.resourceid)
	where capacity>0 and a.resourceid $adder in (".$charr[1]." )
	group by name, a.resourceid, price ";
	
}

function adm_mailbron()
{
	$content="";
	$var = $_REQUEST;
	foreach ( $var as $key => $value ) {
		$$key = trim(htmlspecialchars(strip_tags($value)));}

	

	if ($_REQUEST['message']) 
	{
		wp_mail(  $_REQUEST['to'] , $_REQUEST['subject'], $_REQUEST['message']);
		$content .= "<div class=alert>".__("Message sent","mb-reservation")."</div>"		 ;
	}


	$content.=
	__("Name","mb-reservation").': <b>'.$last_name.' '.$first_name.'</b> , '.__("Order","mb-reservation").' <b>#'.$orderid.'</b> , '.__("Price","mb-reservation").' <b>'.$price.'</b>, '.__("Date start","mb-reservation").' <b>'.$datebegin.'</b> '.__("to","mb-reservation").' <b>'.$dateend.'</b>
	<hr class=res>
	<form action="" method=post>
	'.__("To","mb-reservation").'<br>
	<input type=text name="to" value="'.get_userdata($_REQUEST['userid'])->user_email.'" style="width:515px">
	<br>'.__("Subject","mb-reservation").'<br>
	<input type=text name=subject style="width:515px">
	<br>'.__("Message","mb-reservation").'<br>
	<textarea cols=70 rows=10 name=message></textarea>
	<br><input type=submit class="button-primary" value="'.__("Send","mb-reservation").'">
';

	echo $content;
}

function pro_ordertable()
{
	global $wpdb;
	
	$content = "";
	
	if (isset($_REQUEST['year'])){
	$current_monthstr=strftime("%B",strtotime($_REQUEST['year']."-".$_REQUEST['month']));
	$current_month=strftime("%m",strtotime($_REQUEST['year']."-".$_REQUEST['month']));
	$current_year=strftime("%Y",strtotime($_REQUEST['year']."-".$_REQUEST['month']));}
	else {
	$current_monthstr=strftime("%B");
	$current_month=strftime("%m");
	$current_year=strftime("%Y");
	}
	
	if ($current_month==1) {$prev_month=12; $prev_year=$current_year-1; } else {$prev_month=$current_month-1; $prev_year=$current_year;}
	if ($current_month==12) {$next_month=1; $next_year=$current_year+1; } else {$next_month=$current_month+1; $next_year=$current_year;}
	
	$datebegin=$current_year."-".$current_month."-01";
	$dateend=$current_year."-".$current_month."-".date("t", strtotime($current_year."-".$current_month));
	
	
	if ( isset ($_REQUEST['flagkd']) )	{
	$dateend=date("Y-m-d",strtotime($_REQUEST['dateend'])-1*24*60*60);
	$kolday=$_REQUEST['kolday']=(strtotime($_REQUEST['dateend'])-strtotime($_REQUEST['datebegin']))/(24*60*60);}


	$content .= "<p><br></p>";

	$qry="select a.resourceid, name ,   
	(if ('$datebegin' >= d.datebegin and '$dateend'<= d.dateend, d.price, a.price)) price
	";

	$dt=strtotime ($datebegin);


	$bt = ' <div style="font-size:30px; color:#21759B" align=center>
	<form style="display:inline" method="get">
	<input type=hidden name="page" value="ordertable">
	<input type=hidden name="month" value="'.$prev_month.'">
	<input type=hidden name="year" value="'.$prev_year.'">
	<input class="res-prev"   type="submit" value="'.__("prev","mb-reservation").'"   >
	</form>
	'.$current_monthstr.', '.$current_year.'
	<form style="display:inline" method="get">
	<input type=hidden name="page" value="ordertable">
	<input type=hidden name="month" value="'.$next_month.'">
	<input type=hidden name="year" value="'.$next_year.'">
	<input class="res-next"   type="submit" value="'.__("next","mb-reservation").'"   >
	</form>
	</div><br>
	<table width=100% class="ordertable" > <thead>	<tr ><td style=\"width:200px\" > </td>';
	while (strtotime($dateend)>=$dt)  {
		$qdt=date("Y-m-d",$dt);
		$qdtout=date("d/m",$dt);

		$qry.=",   max( if ( '$qdt' between c.datebegin and c.dateend, CONCAT(c.orderid, ';',(select meta_value from ".$wpdb->prefix ."usermeta f where f.user_id = c.userid and meta_key = 'first_name'),' ',(select meta_value from ".$wpdb->prefix . "usermeta f where f.user_id = c.userid and meta_key = 'last_name')), '')) `$qdt`  ";		
	
		$bt .= "<td  ><a href='admin.php?page=orders&orderd=$qdt'>$qdtout</a></td>";
		$dt=$dt+24*60*60;
	}
	$bt .= '</tr></thead>';
	if ($GLOBALS["version"]	== "pro" && $charr!=0) $qry.=pro_page1_qry($charr); else
	$qry.="   from  
	".$wpdb->prefix . "res_orders  c
INNER JOIN  ".$wpdb->prefix . "res_orders_content   b 
ON (c.orderid =
	b.orderid)
	RIGHT JOIN  ".$wpdb->prefix . "res_resources   a ON (b.resourceid =
	a.resourceid)
	LEFT JOIN ".$wpdb->prefix . "res_offers d ON (d.resourceid = a.resourceid)	
	where capacity>0 
	group by name, a.resourceid, price ";

	$results=$wpdb->get_results($wpdb->prepare($qry), ARRAY_N );

	$rowflag=1;  $j=1;
	if (count($results)>0) {
		
		$content .= $bt;
		foreach ($results as $fld) {
			$content .= '<tr class="rowot'.$rowflag.'">';
			$k=1;
			$min=$fld[3];
			$cflag=0;

			for ($k=0; $k <count($fld); $k++ ) {

				switch ($k) {
				
				case 0:   $resource=$fld[0]; break;
				case 1: $content .= "<td >".$fld[1]."</td>"; break;
				case 2: $price = $fld2;  break;

				default: 
				$client=explode(";",$fld[$k]);
				if ($fld[$k]==$fld[$k+1] and $fld[$k]!="") {$cflag++; continue;}
				else if ($fld[$k]!=$fld[$k+1] and $fld[$k]!="" )  { $cflag++;  $content .= "<td class=\"mark\" colspan=$cflag><a href=\"admin.php?page=orders&ordert=$client[0]\">$client[1]</a></td>"; $cflag=0;}
				if ($fld[$k]=="") $content .= "<td >$fld2</td>"; 
				
				break;
				
				}
				
			}

			
			$content .= '</tr>';			
			$j++;
			$rowflag = $rowflag*(-1);

		}

		$content .= '</table>';			

		
	}
	else $content .= "<p>".__("No information about free resources","mb-reservation")."</p>";
	return $content ;	
	
}	

function pro_confirm_mail($userid, $adm_subject , $adm_message,  $client_subject , $client_message )
{

	$headers = "From: Mikes Bike Tours Amsterdam <".get_option("res_mail_admin_email").">";
	if (wp_mail(  get_option("res_mail_admin_email") , $adm_subject , $adm_message)) {
		; //echo "mail1 sent";
	}
	else {
		;
	}
		

	if (wp_mail(  get_userdata( $userid )->user_email , $client_subject , $client_message)) {
		; //	echo "mail2 sent";
	}
	else {
		;
	}
}

?>